#include "widget_funcc_smart_home.h"
#include <QMessageBox>
#include <QFileDialog>
#include <QTransform>
#include <QDebug>
#include <QGraphicsDropShadowEffect>

Widget_funcC_Smart_Home::Widget_funcC_Smart_Home(QWidget *parent) : QWidget(parent)
{
    //初始化
    initCameraUI();
    initTransformUI();

    // 在构造函数中添加样式表
    this->setStyleSheet(R"(
        QWidget {
            background-color: #f5f7fa;
            font-family: "Microsoft YaHei";
        }

        QPushButton {
            background-color: #4a6baf;
            color: white;
            border: none;
            border-radius: 5px;
            padding: 8px 15px;
            font-size: 14px;
        }

        QPushButton:hover {
            background-color: #5a7bbf;
        }

        QPushButton:pressed {
            background-color: #3a5b9f;
        }

        QPushButton:disabled {
            background-color: #cccccc;
            color: #666666;
        }

        QLabel#imageLabel {
            background-color: #ffffff;
            border: 2px solid #d1d5db;
            border-radius: 8px;
        }

        QCameraViewfinder {
            background-color: #000000;
            border: 2px solid #d1d5db;
            border-radius: 8px;
        }
    )");
}

Widget_funcC_Smart_Home::~Widget_funcC_Smart_Home()
{
    if (camera) {
        camera->stop();
        delete camera;
    }
}

void Widget_funcC_Smart_Home::initCameraUI()
{
    // 摄像头组件初始化
    camera = new QCamera(this);
    viewfinder = new QCameraViewfinder(this);
    viewfinder->setObjectName("viewfinder"); // 为样式表设置对象名
    imageCapture = new QCameraImageCapture(camera);
    camera->setViewfinder(viewfinder);

    // 按钮美化
    startButton = new QPushButton("开启摄像头", this);
    startButton->setFixedSize(120, 40);
    startButton->setIcon(QIcon(":/icons/camera.png")); // 添加图标
    startButton->setIconSize(QSize(20, 20));

    captureButton = new QPushButton("拍照", this);
    captureButton->setFixedSize(120, 40);
    captureButton->setIcon(QIcon(":/icons/capture.png"));
    captureButton->setIconSize(QSize(20, 20));
    captureButton->setEnabled(false);

    // 按钮容器
    QWidget *buttonContainer = new QWidget(this);
    QHBoxLayout *buttonLayout = new QHBoxLayout(buttonContainer);
    buttonLayout->addWidget(startButton);
    buttonLayout->addWidget(captureButton);
    buttonLayout->setSpacing(20);
    buttonLayout->setContentsMargins(0, 0, 0, 0);

    // 设置视图大小（增大摄像头区域）
    viewfinder->setMinimumSize(150, 150);  // 设置最小尺寸
    viewfinder->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
    // 主布局
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->addWidget(viewfinder, 2);  //摄像头区域显示比例值
    mainLayout->addWidget(buttonContainer, 0, Qt::AlignCenter);
    mainLayout->setContentsMargins(20, 20, 20, 20);
    mainLayout->setSpacing(20);

    // 连接信号槽
    connect(startButton, &QPushButton::clicked, this, &Widget_funcC_Smart_Home::toggleCamera);
    connect(captureButton, &QPushButton::clicked, this, &Widget_funcC_Smart_Home::captureImage);

    viewfinder->setVisible(false);
}

void Widget_funcC_Smart_Home::initTransformUI()
{
    // 图片变换按钮美化
    rotateButton = new QPushButton("旋转", this);
    flipButton = new QPushButton("镜像", this);
    grayscaleButton = new QPushButton("灰度化", this);
    resetButton = new QPushButton("重置", this);

    // 设置按钮图标
    rotateButton->setIcon(QIcon(":/翻转"));
    flipButton->setIcon(QIcon(":/镜像"));
    grayscaleButton->setIcon(QIcon(":/阴"));
    resetButton->setIcon(QIcon(":/重来"));

    // 统一按钮大小
    QSize buttonSize(100, 40);
    rotateButton->setFixedSize(buttonSize);
    flipButton->setFixedSize(buttonSize);
    grayscaleButton->setFixedSize(buttonSize);
    resetButton->setFixedSize(buttonSize);

    // 按钮容器
    QWidget *transformButtonContainer = new QWidget(this);
    QHBoxLayout *transformLayout = new QHBoxLayout(transformButtonContainer);
    transformLayout->addWidget(rotateButton);
    transformLayout->addWidget(flipButton);
    transformLayout->addWidget(grayscaleButton);
    transformLayout->addWidget(resetButton);
    transformLayout->setSpacing(15);
    transformLayout->setContentsMargins(0, 0, 0, 0);

    // 图片显示区域美化
    imageLabel = new QLabel(this);
    imageLabel->setObjectName("imageLabel"); // 为样式表设置对象名
    imageLabel->setAlignment(Qt::AlignCenter); //确保内容居中
    imageLabel->setFixedSize(500, 300);
    imageLabel->setScaledContents(false);

    // 图片容器（添加阴影效果）
    QGraphicsDropShadowEffect *shadowEffect = new QGraphicsDropShadowEffect(this);
    shadowEffect->setBlurRadius(15);
    shadowEffect->setColor(QColor(0, 0, 0, 100));
    shadowEffect->setOffset(3, 3);
    imageLabel->setGraphicsEffect(shadowEffect);

    // 主布局调整
    QVBoxLayout *mainLayout = qobject_cast<QVBoxLayout*>(this->layout());
    if (mainLayout) {
        mainLayout->insertWidget(2, imageLabel);

        // 添加变换按钮标题
        QLabel *transformTitle = new QLabel("图片变换", this);
        transformTitle->setAlignment(Qt::AlignCenter); //居中
        transformTitle->setStyleSheet("font-size: 16px; font-weight: bold; color: #333; margin-bottom: 5px;");

        mainLayout->insertWidget(3, transformTitle);
        mainLayout->insertWidget(4, transformButtonContainer);
        mainLayout->setSpacing(15);
    }

    // 连接信号槽
    connect(rotateButton, &QPushButton::clicked, this, &Widget_funcC_Smart_Home::rotateImage);
    connect(flipButton, &QPushButton::clicked, this, &Widget_funcC_Smart_Home::flipImage);
    connect(grayscaleButton, &QPushButton::clicked, this, &Widget_funcC_Smart_Home::grayscaleImage);
    connect(resetButton, &QPushButton::clicked, this, &Widget_funcC_Smart_Home::resetImage);
}

void Widget_funcC_Smart_Home::toggleCamera()
{
    if (!isCameraOn) {
        camera->start();
        viewfinder->setVisible(true);
        startButton->setText("关闭摄像头");
        captureButton->setEnabled(true);
    } else {
        camera->stop();
        viewfinder->setVisible(false);
        startButton->setText("开启摄像头");
        captureButton->setEnabled(false);
    }
    isCameraOn = !isCameraOn;
}

//拍照
void Widget_funcC_Smart_Home::captureImage()
{
    if (imageCapture->isReadyForCapture()) {
        imageCapture->capture();
        connect(imageCapture, &QCameraImageCapture::imageCaptured, this, [this](int id, const QImage &image) {
                currentPixmap = QPixmap::fromImage(image);
                imageLabel->setPixmap(currentPixmap.scaled(imageLabel->size(), Qt::KeepAspectRatio));
            });
    } else {
        QMessageBox::warning(this, "错误", "摄像头未准备好！");
    }
}

//旋转图片
void Widget_funcC_Smart_Home::rotateImage()
{
    if (!currentPixmap.isNull()) {
        QTransform transform;
        transform.rotate(90); // 旋转90度
        currentPixmap = currentPixmap.transformed(transform, Qt::SmoothTransformation);
        imageLabel->setPixmap(currentPixmap.scaled(imageLabel->size(), Qt::KeepAspectRatio));
    }
}

//镜像图片
void Widget_funcC_Smart_Home::flipImage()
{
    if (!currentPixmap.isNull()) {
        currentPixmap = currentPixmap.transformed(QTransform().scale(-1, 1)); // 水平镜像
        imageLabel->setPixmap(currentPixmap.scaled(imageLabel->size(), Qt::KeepAspectRatio));
    }
}

//灰化图片
void Widget_funcC_Smart_Home::grayscaleImage()
{
    // 检查当前是否有有效图片
    if (!currentPixmap.isNull()) {
        // 将QPixmap转换为QImage以便像素级操作
        QImage image = currentPixmap.toImage();

        // 遍历图像每个像素
        for (int y = 0; y < image.height(); y++) {
            for (int x = 0; x < image.width(); x++) {
                // 计算当前像素的灰度值
                int gray = qGray(image.pixel(x, y));
                // 将灰度值应用到RGB三个通道
                image.setPixel(x, y, qRgb(gray, gray, gray));
            }
        }

        // 转换回QPixmap并更新显示
        currentPixmap = QPixmap::fromImage(image);
        imageLabel->setPixmap(currentPixmap.scaled(
            imageLabel->size(),
            Qt::KeepAspectRatio  // 保持宽高比缩放
        ));
    }
}

//重置
void Widget_funcC_Smart_Home::resetImage()
{
    if (!currentPixmap.isNull()) {
        // 重新拍照以重置图片
        captureImage();
    }

}
//#include "widget_funcc_smart_home.h"
//#include "ui_widget_funcc_smart_home.h"
//#include <QUrl>
//#include <QVBoxLayout>
//#include <QGridLayout>

//Widget_funcC_Smart_Home::Widget_funcC_Smart_Home(QWidget *parent) :
//    QWidget(parent),
//    ui(new Ui::Widget_funcC_Smart_Home)
//{
//    ui->setupUi(this);

//    // 调用初始化摄像头UI的函数
//    initCameraUI();

//}
// //声明初始化摄像头UI的函数
////void Widget_funcC_Smart_Home::initCameraUI() {
////    // 1. 初始化摄像头相关对象
////    camera = new QCamera(this);
////    viewfinder = new QCameraViewfinder(this);
////    imageCapture = new QCameraImageCapture(camera);
////    camera->setViewfinder(viewfinder);

////    // 2. 创建按钮并设置图片
////    startButton = new QPushButton(this);

////    // 设置按钮图片（使用 QIcon）
////    QIcon buttonIcon(":/发送"); // 替换为你的图片路径
////    startButton->setIcon(buttonIcon);
////    startButton->setIconSize(QSize(40, 40)); // 调整图标大小

////    // 可选：隐藏按钮文字（如果只需要图标）
////    // startButton->setText("");

////    // 3. 设置布局（使用 QVBoxLayout）
////    QVBoxLayout *mainLayout = new QVBoxLayout(this);

////    // 添加 viewfinder（占满剩余空间）
////    mainLayout->addWidget(viewfinder, 1); // 拉伸因子为1

////    // 添加按钮（固定大小）
////    mainLayout->addWidget(startButton, 0, Qt::AlignCenter); // 不拉伸，居中
////    startButton->setFixedSize(80, 80); // 固定按钮大小

////    // 4. 设置布局的边距和间距（可选）
////    mainLayout->setContentsMargins(10, 10, 10, 10); // 左、上、右、下边距
////    mainLayout->setSpacing(10); // 控件间距

////    // 5. 连接信号槽
////    connect(startButton, &QPushButton::clicked, this, &Widget_funcC_Smart_Home::toggleCamera);

////    // 6. 设置 viewfinder 的背景色（可选）
////    viewfinder->setStyleSheet("background-color: black;");
////    //初始状态：隐藏画面（可选）
////    viewfinder->setVisible(false);
////}

////摄像头初始化
//void Widget_funcC_Smart_Home::initCameraUI() {
//    camera = new QCamera(this);
//    viewfinder = new QCameraViewfinder(this);
//    imageCapture = new QCameraImageCapture(camera);
//    camera->setViewfinder(viewfinder);

//    startButton = new QPushButton("开启摄像头", this);
//    startButton->setFixedSize(80, 80);

//    QVBoxLayout *mainLayout = new QVBoxLayout(this);
//    mainLayout->addWidget(viewfinder, 1); // 画面占满剩余空间
//    mainLayout->addWidget(startButton, 0, Qt::AlignCenter);
//    mainLayout->setContentsMargins(10, 10, 10, 10);

//    connect(startButton, &QPushButton::clicked, this, &Widget_funcC_Smart_Home::toggleCamera);

//    // 初始状态：隐藏画面（可选）
//    viewfinder->setVisible(false);
//    viewfinder->setStyleSheet("background-color: black;");
//}

//Widget_funcC_Smart_Home::~Widget_funcC_Smart_Home()
//{
//    delete ui;
//}

//void Widget_funcC_Smart_Home::changeImage() {
//    QObject *senderobj = sender();  // 获取信号发送者

//    // 判断是哪个标签被点击
//    if (senderobj == ui->label_FloorClean) {
//        // 切换扫地机器人图片
//        ui->label_FloorClean->Set_Image(":/玩家胜利");  // 确保路径正确
//        ui->label_FloorClean->setText("扫地机器人：运行中");
//    }
//    else if (senderobj == ui->label_light) {
//        // 切换灯光图片
//        ui->label_light->Set_Image(":/阴");  // 确保路径正确
//        ui->label_light->setText("灯光：关闭");
//    }

//    // 更新其他状态（如果点击的不是 FloorClean，则更新它的状态）
//    if (senderobj != ui->label_FloorClean) {
//        ui->label_FloorClean->update_start(Mode_No);
//    }
//    if (senderobj != ui->label_light) {
//        ui->label_light->update_start(Mode_No);
//    }
//}
